import android

import time
import json
import sys
import os

script_path = __file__
base_path = os.path.dirname(__file__)
supython_path = os.path.join(base_path, "supython.sh")
scapy_zip_path = os.path.join(base_path, "scapy.zip")
webview_path = os.path.join(base_path, "view.html")
tools_zip_path = os.path.join(base_path, "tools.zip")

# check to see if we're root
if os.getuid() != 0:
    # if we aren't, we'll try to launch the supython script
    os.system("su -c '%s'" % supython_path)
    exit(1)

# initialize our android app
droid = android.Android()
droid.makeToast('Starting Scandy...')


# start our UI
droid.webViewShow('file://%s' % webview_path)


# add the zipped scapy dir to our path
sys.path.insert(1, scapy_zip_path)
sys.path.insert(1, tools_zip_path)


# attempt to import scapy
try:
    import scapy.all as scapy
    droid.log('imported scapy')
except ImportError:
    message = 'Could not import scapy! Aborting!'
    droid.log(message)
    droid.eventPost('setOutput', message)
    exit(1)


# load our tools
try:
    import tools
    droid.log('imported tools')
except ImportError:
    message = 'Could not import tools! Aborting!'
    droid.log(message)
    droid.eventPost('setOutput', message)
    exit(1)


def add_scapy_to_tools():
    # add scapy to the namespace for all of our tools
    for attribute in tools.__all__:
        getattr(tools, attribute).scapy = scapy
        droid.log("added scapy to %s" % attribute)


def add_all_tools():
    for attribute in tools.__all__:
        if attribute == 'api': continue
        html = tools.api.tool_to_HTML(attribute)
        droid.eventPost('addTool', html)
        droid.log("added %s to tool list" % attribute)


def handle_runTask(data):
    droid.log("runTask got %s" % str(data))
    returned = json.loads(data)
    task_name = returned['taskName']
    # filter out the hidden field and submit button
    arguments = returned['arguments'][1:-1]
    droid.log(task_name)
    task = getattr(tools, task_name)
    output = task.run(*arguments)
    droid.log(output)
    droid.eventPost('setOutput', output)


def handle_selectTask(data):
    droid.log("selectTask got data %s" % str(data))
    task_name = data
    module = getattr(tools, task_name)
    arguments = module.ARGUMENTS
    droid.log(task_name)
    form = tools.api.arguments_to_HTML(task_name, arguments)
    droid.eventPost('setInput', form)


def dispatch():
    while True:
        try:
            result = droid.eventWait().result
            event_type = result['name']
            event_data = result['data']
            if event_type == 'runTask':
                handle_runTask(event_data)
            if event_type == 'selectTask':
                handle_selectTask(event_data)
            time.sleep(.2)
        except Exception, e:
            droid.log(str(e))
            

add_scapy_to_tools()
add_all_tools()
dispatch()

    


